package cn.kz.hrm.controller;

import cn.kz.hrm.doc.CourseDoc;
import cn.kz.hrm.query.CourseQuery;
import cn.kz.hrm.repository.CourseElasticsearchRepository;
import cn.kz.hrm.util.AjaxResult;
import cn.kz.hrm.util.PageList;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/elasticresach")
public class ElasticReseachController {

    @Autowired
    private CourseElasticsearchRepository courseElasticsearchRepository;

    /**
     * 添加文档对象。
     * @param courseDoc
     * @return
     */
    @RequestMapping(value = "/save/course", method = RequestMethod.POST)
    public AjaxResult saveElasticReseach(@RequestBody CourseDoc courseDoc) {
        courseElasticsearchRepository.save(courseDoc);
        return AjaxResult.me();
    }

    /**
     * 根据id进行删除数据
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public AjaxResult deleteElasticReseach(@PathVariable long id) {
        courseElasticsearchRepository.deleteById(id);
        return AjaxResult.me();
    }

    /**
     * 根据课程进行管理查询
     * 涉及到的字段有，
     * private String keyword;   //关键字查询
     * private Long productType; //课程类型
     * private String priceMin;  //最小价值
     * private String priceMax;  //最大价值
     * private String sortField; //排序的id，根据哪一个进行排序
     * private String sortType;  //排序的方式，asc 正序，  desc 倒序
     *
     * @param courseQuery
     * @return
     */
    @RequestMapping(value = "/courseQuery", method = RequestMethod.POST)
    public AjaxResult getQueryCourses(@RequestBody CourseQuery courseQuery) {

     /*   //在此处做查询
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();

        //最外层的bool条件查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        //@todo 做过滤查询
        if (courseQuery.getProductType() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("courseTypeId",courseQuery.getProductType()));
        }

        //@todo 做关键字查询 dsl查询
        if(StringUtils.isNotBlank(courseQuery.getKeyword()){
             boolQueryBuilder.must(QueryBuilders.matchQuery("searchField",courseQuery.getKeyword()));
        }

        // @todo dsl过滤根据价格进行过滤查询
        if (courseQuery.getPriceMin() != null) { //最低价
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(courseQuery.getPriceMin()));
        }
        if (courseQuery.getPriceMax() != null) { //最高价
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(courseQuery.getPriceMax()));
        }

        //@todo 分页   默认的起始页是从零开始，所以要进行减一
        builder.withPageable(PageRequest.of(courseQuery.getPage() - 1, courseQuery.getRows()));

        //@todo  排序   获取要排序的字段，根据字段进行排序
        String sortField = courseQuery.getSortField();
        String sortFieldName = "price"; //默认对字段进行排序
        if (StringUtils.isNotBlank(sortField)) {//证明是有排序字段传递，前台的字段与后台的字段不一致，做转换
            switch (sortField.toLowerCase()) {//转换
                case "xl":
                    sortFieldName = "saleCount";
                    break;
                case "xp":
                    sortFieldName = "onlineTime";
                    break;
                case "pl":
                    sortFieldName = "commentCount";
                    break;
            }
        }

        String sortType = courseQuery.getSortType();//获取排序的方式，前端传递asc 或者 desc
        SortOrder sortOrder = SortOrder.ASC;
        sortOrder = StringUtils.isNotBlank(sortType) && sortType.toLowerCase().equals("desc") ? SortOrder.DESC : SortOrder.ASC;
        //排序
        builder.withSort(new FieldSortBuilder(sortFieldName).order(sortOrder));

        //将组合查询放入到builder中
        builder.withQuery(boolQueryBuilder);

        //将准备好的参数进行创建成一个searchQuery对象
        NativeSearchQuery searchQuery = builder.build();
        Page<CourseDoc> courseDocs = courseElasticsearchRepository.search(searchQuery);

        //将结果存放到pagelist中
        PageList<CourseDoc> courseDocPageList = new PageList<>(courseDocs.getTotalElements(), courseDocs.getContent());

        //将courseDocPageList设置给 AjaxResult 返回
        return AjaxResult.me().setResultObj(courseDocPageList);*/


    //1.把courseQeury转成ES的查询对象
    NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
    //==================================================================
    //排序
    String sortField = courseQuery.getSortField();
    if(StringUtils.isNotBlank(sortField)){
    //排序的字段=========================
        String sortFiledName = "price";
        switch (sortField.toLowerCase()) {
            case "xl":
                sortFiledName = "saleCount";
                break;
            case "xp":
                sortFiledName = "onlineTime";
                break;
            case "pl":
                sortFiledName = "commentCount";
                break;
        }

            //排序方式 desc  -> SortOrder.DESC ，asc  -> SortOrder.ASC
            String sortType = courseQuery.getSortType();

            SortOrder sortOrder = SortOrder.ASC;

            sortOrder = StringUtils.isNotBlank(sortType) && sortType.toLowerCase().equals("desc") ? SortOrder.DESC : SortOrder.ASC;

            builder.withSort(new FieldSortBuilder(sortFiledName).order(sortOrder));
         }
        //分页
        builder.withPageable(PageRequest.of(courseQuery.getPage()-1,courseQuery.getRows()));

        //boolean组合查询
         BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if(StringUtils.isNotBlank(courseQuery.getKeyword())){
            //DSL查询 ： keyword -> must -> matchQuery
            boolQueryBuilder.must(QueryBuilders.matchQuery("searchField", courseQuery.getKeyword()));
        }
        if(null!=courseQuery.getProductType()) {
            //DSL过滤 : productType -> term
            boolQueryBuilder.filter(QueryBuilders.termQuery("courseTypeId", courseQuery.getProductType()));
        }
        if(null!=courseQuery.getPriceMin()){
            //DSL过滤 : priceMax;priceMin -> range
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(courseQuery.getPriceMin()));
        }
        if(null!=courseQuery.getPriceMax()){
        //DSL过滤 : priceMax;priceMin -> range
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(courseQuery.getPriceMax()));
        }
        builder.withQuery(boolQueryBuilder);
        //==================================================================
        //2.调用courseElasticsearchRepository进行查询
        Page<CourseDoc> page = courseElasticsearchRepository.search(builder.build());

        //3.把结果封装成 PageList<CourseDoc> ，设置给 AjaxResult 返回
        return AjaxResult.me().setResultObj(new PageList<CourseDoc>(page.getTotalElements(),page.getContent()));

    }
}
